import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:steam_app/config/app_routes.dart';
import '../../config/app_theme.dart';
import '../../provider/user_provider.dart';
import '../widgets/user_avatar.dart';

class TokenPage extends StatefulWidget {
  const TokenPage({super.key});

  @override
  State<TokenPage> createState() => _TokenPageState();
}

class _TokenPageState extends State<TokenPage> {
  bool showToken = false;
  String verificationCode = '';
  double progress = 1.0;
  Timer? timer;
  static const int intervalSeconds = 10;
  int secondsLeft = intervalSeconds;

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  void startTimer() {
    generateCode();
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        secondsLeft--;
        progress = secondsLeft / intervalSeconds;
        if (secondsLeft <= 0) {
          generateCode();
          secondsLeft = intervalSeconds;
          progress = 1.0;
        }
      });
    });
  }

  void generateCode() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    final rand = Random();
    verificationCode = String.fromCharCodes(
      List.generate(5, (index) => chars.codeUnitAt(rand.nextInt(chars.length))),
    );
  }

  @override
  Widget build(BuildContext context) {
    final user = context.watch<UserProvider>().currentUser;

    if (user == null) {
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('STEAM 令牌'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(hPaddingSize),
        child: Column(
          children: [
            const SizedBox(height: 16),
            const Text(
              '输入此代码，确认您用以下身份登录：',
              style: TextStyle(color: Colors.white70),
            ),
            const SizedBox(height: 12),
            _buildUserInfoTile(user),
            const SizedBox(height: 20),
            if (!showToken) _buildSecurityNotice(),
            const SizedBox(height: 20),
            if (!showToken)
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    showToken = true;
                    startTimer();
                  });
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: blueButtonColor,
                  foregroundColor: textColor,
                  minimumSize: const Size(double.infinity, 48),
                ),
                child: const Text('显示 Steam 令牌验证码'),
              ),
            if (showToken) _buildTokenDisplay(),
          ],
        ),
      ),
    );
  }

  Widget _buildUserInfoTile(user) {
    return InkWell(
      onTap: () => _showAccountSwitchSheet(),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: blueButtonColor,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            UserAvatar(user: user, radius: 22),
            const SizedBox(width: 12),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(user.name,
                    style: const TextStyle(
                        fontWeight: titleFontWeight,
                        fontSize: titleFontSize,
                        color: textColor)),
                Text(user.account, style: const TextStyle(color: textColor)),
              ],
            ),
            const Spacer(),
            const Icon(Icons.keyboard_arrow_down, color: textColor),
          ],
        ),
      ),
    );
  }

  Widget _buildSecurityNotice() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey.shade900,
        borderRadius: BorderRadius.circular(8),
      ),
      child: const Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('安全注意事项：',
              style: TextStyle(fontWeight: titleFontWeight, color: textColor)),
          SizedBox(height: 8),
          Text(
            '只有在您的手机无法访问互联网时才需输入代码。\n永远不要把您的代码给另一个用户或网站。',
            style: TextStyle(color: Colors.white70),
          ),
        ],
      ),
    );
  }

  Widget _buildTokenDisplay() {
    return Expanded(
      child: Center(
        child: Stack(
          alignment: Alignment.center,
          children: [
            SizedBox(
              width: 300,
              height: 300,
              child: CircularProgressIndicator(
                value: progress,
                strokeWidth: 10,
                backgroundColor: Colors.lightBlue,
                valueColor: const AlwaysStoppedAnimation<Color>(Colors.black45),
              ),
            ),
            GestureDetector(
              onTap: () {},
              child: Text(
                verificationCode,
                style: const TextStyle(
                  fontSize: 34,
                  color: textColor,
                  fontWeight: titleFontWeight,
                  letterSpacing: 5,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showAccountSwitchSheet() {
    final user = context.read<UserProvider>().currentUser;

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.grey[900],
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) {
        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              UserAvatar(user: user, radius: 24),
              const SizedBox(height: 8),
              Text(user!.name,
                  style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.white)),
              Text(user.account, style: const TextStyle(color: Colors.white70)),
              const SizedBox(height: 16),
              ListTile(
                leading: const Icon(Icons.add, color: textColor),
                title: const Text('添加帐户',
                    style: TextStyle(color: textColor)),
                onTap: () {
                  Navigator.pop(context);
                  Navigator.pushNamed(context, register_page);
                },
              ),
              const SizedBox(height: 8),
            ],
          ),
        );
      },
    );
  }
}
